import { defineStore } from 'pinia'

export const useTagsStore = defineStore('tags', {
  state: () => {
    return {
      // 存放浏览组件的路由信息
      visitedViews: [],
      // 存放缓存组件的name; 组件需要保持name选项与菜单信息name一致
      cachedViews: [],
    }
  },
  actions: {
    addVisitedView(view) {
      console.log(view)
      if (this.visitedViews.some(item => item.path === view.path)) return;
      this.visitedViews.push(
        Object.assign({}, view)
      )
    },
    addCachedView(view) {
      if (this.cachedViews.includes(view.name)) return;
      if (!view.meta.noCache) {
        this.cachedViews.push(view.name)
      }
    },
    delVisitedView(view) {
      for (const [i, v] of this.visitedViews.entries()) {
        if (v.path === view.path) {
          this.visitedViews.splice(i, 1)
          break
        }
      }
    },
    delCachedView(view) {
      const index = this.cachedViews.indexOf(view.name)
      if (index > -1) {
        this.cachedViews.splice(index, 1)
      }
    },
    delOthersViews(view) {
      this.visitedViews = this.visitedViews.filter(item => {
        return item.meta.affix || item.path === view.path
      })
      // 清除缓存还有问题
      const index = this.cachedViews.indexOf(view.name)
      if (index > -1) {
        this.cachedViews = this.cachedViews.filter(item => item !== view.name)
      } else {
        this.cachedViews = []
      }
    },
    delAllViews() {
      const affixTags = this.visitedViews.filter(view => view.meta.affix)
      this.visitedViews = affixTags;
      this.cachedViews = [];
    }
  }
})